package com.alvis.exam.controller.admin;

import com.alvis.exam.base.BaseApiController;
import com.alvis.exam.base.RestResponse;
import com.alvis.exam.base.SystemCode;
import com.alvis.exam.domain.TClass;
import com.alvis.exam.domain.TStudent;
import com.alvis.exam.domain.User;
import com.alvis.exam.service.ClassService;
import com.alvis.exam.service.StudentService;
import com.alvis.exam.service.UserService;
import com.alvis.exam.utility.ErrorUtil;
import com.alvis.exam.viewmodel.admin.administration.ClassEditRequestVM;
import com.alvis.exam.viewmodel.admin.administration.ClassPageRequestVM;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/api/admin/class")
@Validated
public class ClassController extends BaseApiController {

    @Autowired
    private ClassService service;

    @Autowired
    private StudentService studentService;

    @PostMapping("/page")
    public Object page(@RequestBody ClassPageRequestVM model) {
        return RestResponse.okList(service.querySelective(model));
    }

    @PostMapping("/batchCreate")
    public Object batchCreate() {
        service.deleteAll();
        List<TClass> classes = studentService.getAllClass();
        service.saveOrUpdateBatch(classes);
        return RestResponse.ok();
    }

    @PostMapping("/delete/{id}")
    public RestResponse delete(@PathVariable Integer id) {
        service.deleteById(id);
        return RestResponse.ok();
    }

    @PostMapping("/select/{id}")
    public Object select(@PathVariable Integer id) {
        TClass tClass = service.selectById(id);
        return RestResponse.ok(tClass);
    }

    @PostMapping("/edit")
    public RestResponse edit(@RequestBody @Valid ClassEditRequestVM model) {
        if (!service.isClassNameValid(model)) {
            String errorMsg = ErrorUtil.parameterErrorFormat("行政班名", "已经存在!");
            return new RestResponse<>(SystemCode.ParameterValidError.getCode(), errorMsg);
        }

        if (Objects.nonNull(model.getMonitor())){
            TStudent student = studentService.selectById(model.getMonitor());
            if (Objects.isNull(student) || !StringUtils.equals(student.getClassName(), model.getName())){
                String errorMsg = ErrorUtil.parameterErrorFormat("班长", "不是该行政班成员!");
                return new RestResponse<>(SystemCode.ParameterValidError.getCode(), errorMsg);
            }
        }

        TClass tClass = modelMapper.map(model, TClass.class);
        if (null == tClass.getId()) {
            tClass.setDeleted(false);
            service.insert(tClass);
        } else {
            service.updateById(tClass);
        }

        return RestResponse.ok();
    }
}
